﻿<template>
  <div class="app-container">
    <el-dialog
      title="确认要删除此项吗？"
      :visible.sync="delDialogVisible"
      width="30%"
      :append-to-body="true"
    >
      <span slot="footer">
        <el-button size="small" @click="delDialogVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="delSelect">确 定</el-button>
      </span>
    </el-dialog>

    <el-card>
      <div class="ly-tree-container">
        <el-tree
          :data="categories"
          :props="defaultProps"
          node-key="id"
          default-expand-all
          :expand-on-click-node="false"
          :render-content="renderContent"
        />
      </div>
    </el-card>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="150px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="编码" prop="code">
          <el-input v-model="temp.code" />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button :loading="loading" type="primary" @click="dialogStatus==='create'?createData():updateData()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getListPaged, create, get, update, remove } from '@/api/authserver/department'
import { getEditContent, getDefaultContent } from './utils.js'
// import waves from '@/directive/waves' // waves directive
// import { parseTime } from '@/utils'
// import Pagination from '@/components/Pagination' // secondary package based on el-pagination
// import { checkPhone } from '@/utils/validate'

export default {
  name: 'Department',
  components: { },
  directives: { },
  data() {
    return {
      isEdit: false,
      edit_name: '',
      is_superuser: 'False',
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      select_id: null,
      select_level: null,
      select_node: null,
      delDialogVisible: false,
      categories: [],
      dialogStatus: '',
      dialogFormVisible: false,
      loading: false,
      temp: {
        id: '',
        code: '',
        parentId: '',
        name: ''
      },
      textMap: {
        update: '编辑部门',
        create: '添加部门'
      },
      rules: {
        code: [{ required: true, message: '编码', trigger: 'blur' }],
        name: [{ required: true, message: '名称', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      const params = {
        sorting: '',
        skipCount: 0,
        maxResultCount: 200
      }
      getListPaged(params).then(response => {
        var rootNode = {
          name: '部门',
          id: null,
          level: 0,
          isEdit: false,
          children: []
        }
        this.categories = [rootNode]
        if (response && response.data && response.data.items && response.data.items.length > 0) {
          this.generateNode(response.data.items, rootNode)
          this.categories = [rootNode]
        }
      }).finally(() => { this.listLoading = false })
    },
    generateNode(list, rootNode) {
      list.forEach(a => {
        if (a.parentId === rootNode.id) {
          var node = {
            name: a.name + '[' + a.code + ']',
            id: a.id,
            level: rootNode.level + 1,
            isEdit: false,
            children: []
          }
          rootNode.children.push(node)
          if (list.some(s => s.parentId === a.id)) {
            this.generateNode(list, node)
          }
        }
      })
    },
    resetTemp() {
      this.temp = {
        id: '',
        parentId: '',
        code: '',
        name: ''
      }
    },
    handleCreate(parentId) {
      this.resetTemp()
      this.temp.parentId = parentId
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.loading = true
          create(this.temp).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '添加部门成功',
              type: 'success',
              duration: 2000
            })
          }).catch(err => {
            console.log(err)
          }).finally(() => {
            this.loading = false
          })
        }
      })
    },
    handleUpdate(row) {
      const { id } = row
      get(id).then(response => {
        this.temp.id = response.data.id
        this.temp.parentId = response.data.parentId
        this.temp.code = response.data.code
        this.temp.name = response.data.name
        this.dialogStatus = 'update'
        this.dialogFormVisible = true

        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.loading = true
          const id = this.temp.id
          const data = {
            parentId: this.temp.parentId,
            code: this.temp.code,
            name: this.temp.name
          }
          update(id, data).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
          }).finally(() => {
            this.loading = false
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将删除该客户类别, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        const { id } = row
        remove(id).then(() => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })
      }).catch(err => {
        console.log(err)
      })
    },
    append(node, data, e) {
      this.handleCreate(data.id)
    },
    remove(node, data, e) {
      e = event || window.event
      e.stopPropagation()
      if (this.isEdit) {
        this.$notify({
          type: 'error',
          title: '操作提示',
          message: '有正在编辑或添加的选项未完成！',
          duration: 2000
        })
        return
      }
      this.select_node = node
      this.delDialogVisible = true
    },

    delSelect() {
      remove(this.select_node.data.id).then(() => {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        this.getList()
      })
      this.delDialogVisible = false
    },
    update(node, data, e) {
      this.handleUpdate(data)
    },
    editMsg(data, node, e) {
      e = event || window.event
      e.stopPropagation()
      if (this.edit_name.replace(/^\s+|\s+$/g, '')) {
        if (!data.id) {
          const virtualNode = node.parent
          const params = {
            name: this.edit_name,
            parentId: virtualNode.data.id
          }

          create(params).then(() => {
            this.getList()
            this.$notify({
              title: '成功',
              message: '添加部门成功',
              type: 'success',
              duration: 2000
            })
          }).catch(err => {
            console.log(err)
          })
        } else {
          const virtualNode = node.parent
          const params = {
            name: this.edit_name,
            parentId: virtualNode.data.id
          }
          update(data.id, params).then(() => {
            this.getList()
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      }

      this.isEdit = false
      this.select_id = null
      this.select_level = null
    },
    close(data, node, e) {
      e = event || window.event
      e.stopPropagation()
      if (!data.id) {
        node.parent.data.children.forEach((item, i) => {
          if (!item.id) {
            node.parent.data.children.splice(i, 1)
          }
        })
      }
      this.select_id = null
      this.select_level = null
      this.edit_name = data.name
      this.isEdit = false
    },

    nameChange(e) {
      e = event || window.event
      e.stopPropagation()
      this.edit_name = e.target.value
    },
    isSelect(data) {
      return data.id === this.select_id && data.level === this.select_level
    },
    renderContent(h, { node, data }) {
      return (
        <span class='ly-tree-node'>
          {(this.isEdit === true && this.isSelect(data)) || data.isEdit ? (
            <input
              placeholder='名称不能为空'
              class='ly-edit__text'
              on-keyup={() => this.nameChange()}
              value={this.edit_name}
            />
          ) : (
            <span>{data.name}</span>
          )}
          {(this.isEdit === true && this.isSelect(data)) || data.isEdit
            ? getEditContent.call(this, h, data, node)
            : getDefaultContent.call(this, h, data, node)}
        </span>
      )
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
/deep/ .ly-tree-container {
  margin: 20px 0 20px 20px;
  width: 60%;
  padding: 20px;

  span {
    font-size: 14px;
  }

  .el-tree > .el-tree-node > .el-tree-node__content:first-child {
    &::before,
    &::after {
      border: none;
    }
  }

  .ly-visible {
    margin-left: 50px;
    visibility: hidden;
  }

  .ly-edit__text {
    width: 25%;
    height: 25px;
    border: 1px solid #e6e6e6;
    border-radius: 3px;
    color: #666;
    text-indent: 10px;
  }

  .ly-tree__loading {
    color: #666;
    font-weight: bold;
  }

  .ly-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    // justify-content: space-between;
    justify-content: flex-start;
    font-size: 14px;
    padding-right: 8px;
  }

  .ly-tree-node > div > span:last-child {
    display: inline-block;
    width: 110px;
    text-align: left;
  }

  .ly-tree-node > span:last-child {
    display: inline-block;
    width: 110px;
    text-align: left;
  }

  .el-tree-node .el-tree-node__content {
    height: 30px;

    &:hover .ly-visible {
      visibility: visible;
    }

    &::before,
    &::after {
      content: '';
      position: absolute;
      right: auto;
    }

    &::before {
      border-left: 1px solid #e6e6e6;
      bottom: 50px;
      height: 100%;
      top: 0;
      width: 1px;
      margin-left: -5px;
      margin-top: -15px;
    }

    &::after {
      border-top: 1px solid #e6e6e6;
      height: 20px;
      top: 14px;
      width: 10px;
      margin-left: -5px;
    }
  }

  .el-tree .el-tree-node {
    position: relative;
  }
}
}
</style>
